package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.entity.PaGreetings;
import cn.chinaflame.pagodas.repository.PaGreetingsRepository;
import cn.chinaflame.pagodas.req.PaGreetingsReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.UpdateTool;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;

/**
 * Created by yw on 2018/9/27.
 */
@Service
public class PaGreetingsService {

    private static Logger log = LoggerFactory.getLogger(PaGreetingsService.class);
    @Autowired
    private PaGreetingsRepository paGreetingsRepository;
    @Autowired
    private IdGeneratorService idGeneratorService;


    public Object add (PaGreetingsReq req) {
        log.info("祝福语添加service req:{}", req);
        try {
            req.check();
            String id = idGeneratorService.generateIdByTableName("pa_greetings");
            req.setId(Integer.valueOf(id));
            req.setStatus("0");
            req.setCreatetime(DateTimes.nowDateTime());
            req.setUpdatetime(DateTimes.nowDateTime());
            PaGreetings paGreetings = new PaGreetings();
            BeanUtils.copyProperties(req,paGreetings);
            paGreetings = paGreetingsRepository.save(paGreetings);
            return Result.create(paGreetings);
        }catch (Exception e) {
            log.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "添加祝福语失败");
    }

    public Object update (PaGreetingsReq req) {
        log.info("祝福语修改service req:{}", req);
        try{
            req.check();
            req.setUpdatetime(DateTimes.nowDateTime());
            PaGreetings paGreetings = new PaGreetings();
            paGreetings = paGreetingsRepository.findOne(req.getId());
            //更新处理字段为空的数据库一起更新
            UpdateTool.copyNullProperties(paGreetings, req);
            BeanUtils.copyProperties(req,paGreetings);
            paGreetings = paGreetingsRepository.save(paGreetings);
            return Result.create(paGreetings);
        }catch (Exception e) {
            log.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "修改祝福语失败");
    }

    public Object delete (Integer id) {
        log.info("祝福语删除service id:{}", id);
        try{
            PaGreetings paGreetings = new PaGreetings();
            paGreetings.setId(id);
            paGreetings.setStatus("1");
            paGreetings.setUpdatetime(DateTimes.nowDateTime());
            paGreetings = paGreetingsRepository.save(paGreetings);
            return Result.create(paGreetings);
        }catch (Exception e) {
            log.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "修改祝福语失败");
    }

    public Object query (Integer id) {
        log.info("祝福语查看详情service id:{}", id);
        try{
            PaGreetings paGreetings = new PaGreetings();

            paGreetings = paGreetingsRepository.findOne(id);
            return Result.create(paGreetings);
        }catch (Exception e) {
            log.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "查看祝福语失败");
    }

    public Object list (String pageIndex,String pageSize,String id, String greetings) {
        log.info("祝福语List查询service pageIndex:{},pageSize:{},id:{},greetings:{}", pageIndex,pageSize,id,greetings);
        try{
            if (pageIndex != null && pageSize != null) {
                Pageable pageable = new PageRequest(Integer.valueOf(pageIndex)-1, Integer.valueOf(pageSize), new Sort(Sort.Direction.DESC, "id"));
                Page<PaGreetings> paGreetings = paGreetingsRepository.findAll(new Specification<PaGreetings>() {
                    @Override
                    public Predicate toPredicate(Root<PaGreetings> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                        List<Predicate> list = Lists.newArrayList();
                        if (!StringUtils.isEmpty(id)){
                            list.add(cb.equal(root.get("id").as(String.class), id));
                        }
                        if (!Strings.isNullOrEmpty(greetings)){
                            list.add(cb.equal(root.get("greetings").as(String.class), greetings));
                        }
                        list.add(cb.equal(root.get("status").as(String.class), "0"));
                        Predicate[] p = new Predicate[list.size()];
                        return cb.and(list.toArray(p));
                    }
                },pageable);
                List<PaGreetings> list = paGreetings.getContent();
                Map<String,Object> map = Maps.newHashMap();
                map.put("list",list);
                map.put("count",paGreetings.getTotalElements());
                return Result.create(map);
            }
            List<PaGreetings> paGreetings = paGreetingsRepository.findAll(new Specification<PaGreetings>() {
                @Override
                public Predicate toPredicate(Root<PaGreetings> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> list = Lists.newArrayList();
                    if (!StringUtils.isEmpty(id)){
                        list.add(cb.equal(root.get("id").as(String.class), id));
                    }
                    if (!Strings.isNullOrEmpty(greetings)){
                        list.add(cb.equal(root.get("greetings").as(String.class), greetings));
                    }
                    list.add(cb.equal(root.get("status").as(String.class), "0"));
                    Predicate[] p = new Predicate[list.size()];
                    return cb.and(list.toArray(p));
                }
            });
            Map<String,Object> map = Maps.newHashMap();
            map.put("list",paGreetings);
            map.put("count",paGreetings.size());
            return Result.create(map);
        }catch (Exception e) {
            log.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "查看祝福语失败");
    }



}
